/*******************************************************************************
 * Copyright (c) 2007 University of Oslo.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     University of Oslo - initial API and implementation
 *******************************************************************************/

package com.cea.papyrus.diagram.sequence.sedi.editor;

import org.eclipse.gef.EditPart;
import org.eclipse.gef.EditPartViewer;
import org.eclipse.gef.requests.CreateRequest;
import org.eclipse.gef.requests.CreationFactory;
import org.eclipse.gef.tools.ConnectionCreationTool;

public class SeDiConnectionCreationTool  extends ConnectionCreationTool {

	public SeDiConnectionCreationTool() {
		setUnloadWhenFinished(true);
	}
	public SeDiConnectionCreationTool(CreationFactory factory) {
		this();
        setFactory(factory);
	}
	
	// This method provides automatic selection of the new connection
	protected boolean handleCreateConnection() {
		final boolean created = super.handleCreateConnection();
		if (created)
			selectAddedObject(getCurrentViewer());
		return created;
	}

	// This method corresponds to CreationTool#selectAddedObject 
	private void selectAddedObject(EditPartViewer viewer) {
		final Object model = getCreateRequest().getNewObject();
		if (model == null || viewer == null)
			return;
		Object editpart = viewer.getEditPartRegistry().get(model);
		if (editpart instanceof EditPart) {
			//Force the new object to get positioned in the viewer. 
			viewer.flush();
			viewer.select((EditPart)editpart);
		}
	}
	
	// This method corresponds to CreationTool#getCreateRequest 
	protected CreateRequest getCreateRequest() {
		return (CreateRequest)getTargetRequest();
	}	
}
